
<?php
function GetSaltForSystem($username)
{
	$crypt_string = GetUserSaveInfo($username);
	
	$salt_string = substr($crypt_string, 0, CRYPT_SALT_LENGTH);
	return $salt_string;
}

function CreatSaltForSystem()
{
        for ($n = 0; $n < (CRYPT_SALT_LENGTH - 4); $n ++)
	{
        	$s .= chr(rand(64,126));
        }
        $seed =  "$1$".$s."$";
	return $seed;
}

function GetUserSaveInfo($username)
{
	$buffer_len = 1024;
	$ret_string = "";
	$handle = @fopen("/etc/shadow", "r");
	if ($handle) 
	{
   		while (!feof($handle)) 
		{
          		$buffer = fgets($handle, $buffer_len);
	         	$array = explode(":",$buffer);
			for($i = 0; $i<count($array); $i++)   
			{  
				if ($array[0] ==  $username)
				{
					$ret_string = $array[1];
					break;
				}
			}   
			if ($ret_string != "")
				break;
		}
		fclose($handle);
	}
	return $ret_string;
}

function CheckSysPassWord($passwd, $username)
{
	$salt_string = GetSaltForSystem($username);
	$crypt_string = GetUserSaveInfo($username);
	$hash = crypt($passwd, $salt_string);
	
	if ($crypt_string == $hash)
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

function ModifyShadowForPassWord($username, $crypt_string)
{
	$buffer_len = 1024;

	$handle_read = @fopen("/etc/shadow", "r");
	$handle_write = @fopen("/etc/shadow.tmp", "w+");
	if ($handle_read && $handle_write) 
	{
   		while (!feof($handle_read)) 
		{
          		$buffer = fgets($handle_read, $buffer_len);
	         	$array = explode(":",$buffer);

			for($i = 0; $i < count($array); $i ++)   
			{  
				if ($array[0] ==  $username)
				{
					$array[1] = $crypt_string;
					$buffer = "";
					for ( $k = 0; $k < count($array); $k ++)
					{
						$buffer = $buffer. $array[$k]. ":";
					}
					break;
				}
			} 
			if (fwrite($handle_write, $buffer) === FALSE) 
				return ;
		}
		fclose($handle_read);
		fclose($handle_write);
	}
}

function ModifySysPassWord($passwd_new, $passwd_old, $username)
{
	if ( !CheckSysPassWord($passwd_old, $username))
	{
		return ;
	}
	$crypt_string = crypt($passwd_new, GetSaltForSystem($username));
	ModifyShadowForPassWord($username, $crypt_string);
	#rename( '/etc/shadow.tmp', '/etc/shadow' );
	for ($i = 0; $i < 4; $i ++)
	{
		system ("sync");
	}	
}

function AddSysUser($passwd, $username)
{
	$crypt_string = crypt($passwd, CreatSaltForSystem());
	$handle_passwd = 
	$handle_shadow = 
	$user_shell = "/bin/sh";
	$user_id = rand(2000,6000);
	$passwd_string = $username. ":x:". $user_id. ":". $user_id. "::/tmp:". $user_shell;
	#print $passwd_string . "\n";

	$shadow_string = $username. ":". $crypt_string. ":". $user_id. ":0:99999:7:::";
	#print $shadow_string . "\n";
}
#AddSysUser("123456","root");


?>
